package com.fjh.springboot_01.service.impl;

import com.fjh.springboot_01.mapper.TutoringMapper;
import com.fjh.springboot_01.mapper.TutoringBookingMapper;
import com.fjh.springboot_01.mapper.TutoringScheduleMapper;
import com.fjh.springboot_01.pojo.tutor.Tutoring;
import com.fjh.springboot_01.pojo.tutor.TutoringBooking;
import com.fjh.springboot_01.pojo.tutor.TutoringSchedule;
import com.fjh.springboot_01.service.TutoringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;

@Service
public class TutoringServiceImpl implements TutoringService {
    @Autowired
    private TutoringMapper tutoringMapper;
    
    @Autowired
    private TutoringBookingMapper bookingMapper;

    @Autowired
    private TutoringScheduleMapper scheduleMapper;

    @Override
    public void publishTutoring(Tutoring tutoring) {
        tutoring.setStatus(1); // 设置为可用状态
        tutoringMapper.insert(tutoring);
    }

    @Override
    public List<Tutoring> getAllActiveTutoring() {
        return tutoringMapper.findAllActive();
    }

    @Override
    public List<Tutoring> getAllActiveTutoringWithTeacherInfo() {
        return tutoringMapper.findAllActiveWithTeacherInfo();
    }

    @Override
    public List<Tutoring> getTeacherTutoring(Integer teacherId) {
        return tutoringMapper.findByTeacherId(teacherId);
    }

    @Override
    public Tutoring getTutoringById(Integer id) {
        return tutoringMapper.findById(id);
    }

    @Override
    public void updateTutoringStatus(Integer id, Integer status) {
        tutoringMapper.updateStatus(id, status);
    }

    @Override
    public void updateTutoring(Tutoring tutoring) {
        tutoring.setUpdateTime(LocalDateTime.now());
        tutoringMapper.update(tutoring);
    }

    @Override
    public void createBooking(TutoringBooking booking) {
        // 验证tutoring_id对应的家教信息是否存在且状态为可用
        Tutoring tutoring = tutoringMapper.findById(booking.getTutoringId());
        if (tutoring == null) {
            throw new RuntimeException("未找到对应的家教信息");
        }
        
        if (tutoring.getStatus() != 1) {
            throw new RuntimeException("该家教信息当前不可预约");
        }
        
        // 验证教师ID是否与家教信息中的教师ID一致
        if (!booking.getTeacherId().equals(tutoring.getTeacherId())) {
            throw new RuntimeException("家教教师信息不匹配");
        }
        
        booking.setStatus(0); // 设置为待确认状态
        bookingMapper.insert(booking);
    }

    @Override
    public List<TutoringBooking> getTeacherBookings(Integer teacherId) {
        return bookingMapper.findByTeacherId(teacherId);
    }

    @Override
    public List<TutoringBooking> getStudentBookings(Integer studentId) {
        return bookingMapper.findByStudentId(studentId);
    }

    @Override
    public void updateBookingStatus(Integer id, Integer status) {
        bookingMapper.updateStatus(id, status);
    }

    @Override
    public TutoringBooking getBookingById(Integer id) {
        return bookingMapper.findById(id);
    }
    
    @Override
    public List<Tutoring> getLatestTutoring(int limit) {
        return tutoringMapper.findLatest(limit);
    }
    
    @Override
    public Map<String, Integer> getSubjectStatistics() {
        List<Map<String, Object>> stats = tutoringMapper.getSubjectStatistics();
        Map<String, Integer> result = new HashMap<>();
        
        for (Map<String, Object> stat : stats) {
            String subject = (String) stat.get("subject");
            Integer count = ((Number) stat.get("count")).intValue();
            result.put(subject, count);
        }
        
        return result;
    }
    
    @Override
    public int getTutoringCount() {
        return tutoringMapper.getTotalCount();
    }
    
    @Override
    public int getCompletedTutoringCount() {
        // 从家教预约表中获取已完成的家教数量（status = 3）
        return bookingMapper.getCompletedBookingCount();
    }

    @Override
    public List<Tutoring> getStudentConfirmedTutorings(Integer studentId) {
        // 获取学生已确认预约的教师ID列表
        List<Integer> teacherIds = bookingMapper.findConfirmedTeacherIdsByStudentId(studentId);
        
        System.out.println("学生ID: " + studentId + " 已确认预约的教师IDs: " + teacherIds);
        
        if (teacherIds == null || teacherIds.isEmpty()) {
            System.out.println("学生没有已确认的预约");
            return new ArrayList<>();
        }
        
        // 获取这些教师的可用课程
        List<Tutoring> tutorings = tutoringMapper.findByTeacherIdsAndActive(teacherIds);
        System.out.println("找到的课程数量: " + tutorings.size());
        
        return tutorings;
    }

    @Override
    public void teacherDeleteBooking(Integer id) {
        // 标记为教师已删除
        bookingMapper.markTeacherDeleted(id);
        // 尝试彻底删除（只有当学生也删除了才会真正删除）
        bookingMapper.deleteById(id);
    }

    @Override
    public void studentDeleteBooking(Integer id) {
        // 标记为学生已删除
        bookingMapper.markStudentDeleted(id);
        // 尝试彻底删除（只有当教师也删除了才会真正删除）
        bookingMapper.deleteById(id);
    }

    /**
     * 根据学生ID和教师ID查找有效的预约
     * @param studentId 学生ID
     * @param teacherId 教师ID
     * @return 预约信息
     */
    @Override
    public TutoringBooking findBookingByStudentAndTeacherId(Integer studentId, Integer teacherId) {
        // 查询学生和教师之间已确认的预约
        return bookingMapper.findBookingByStudentAndTeacherId(studentId, teacherId);
    }

    /**
     * 获取课程安排详情
     * @param id 课程安排ID
     * @return 课程安排信息
     */
    @Override
    public TutoringSchedule getScheduleById(Integer id) {
        return scheduleMapper.selectById(id);
    }

    @Override
    public List<Tutoring> getAllTutoring() {
        return tutoringMapper.findAll();
    }
} 